package com.ruoyi.index.service.impl;

import com.cyl.manager.act.domain.entity.FhMypunctuation;
import com.cyl.manager.act.service.FhMypunctuationService;
import com.cyl.manager.ums.domain.entity.UserInfo;
import com.github.pagehelper.PageHelper;
import com.ruoyi.chat.domain.FhChatFriend;
import com.ruoyi.chat.mapper.FhChatFriendMapper;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.framework.config.LocalDataUtil;
import com.ruoyi.index.domain.FhIndexPostinfo;
import com.ruoyi.index.domain.FhIndexPostinfoAndIsLike;
import com.ruoyi.index.dto.FhIndexPostinfoVO;
import com.ruoyi.index.dto.FhMapFishtypeDto;
import com.ruoyi.index.dto.PostInfoDtoX;
import com.ruoyi.index.dto.PostinfoDto;
import com.ruoyi.index.mapper.FhIndexPostinfoMapper;
import com.ruoyi.index.service.IFhIndexPostinfoService;
import com.ruoyi.map.domain.FhMapFishtype;
import com.ruoyi.map.domain.ScreeningCatchDto;
import com.ruoyi.map.domain.TimeDto;
import com.ruoyi.map.mapper.FhMapFishtypeMapper;
import com.ruoyi.web.core.config.LocalUserInfoUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;

/**
 * 发布信息Service业务层处理
 *
 * @author ruoyi
 * @date 2024-11-12
 */
@Service
public class FhIndexPostinfoServiceImpl implements IFhIndexPostinfoService
{
    @Autowired
    private FhIndexPostinfoMapper fhIndexPostinfoMapper;
    @Autowired
    private FhChatFriendMapper fhChatFriendMapper;
    @Autowired
    private FhMapFishtypeMapper fhMapFishtypeMapper;
    @Autowired
    private FhMypunctuationService fhMypunctuationService;

    /**
     * 查询发布信息
     *
     * @param id 发布信息主键
     * @return 发布信息
     */
    @Override
    public FhIndexPostinfo selectFhIndexPostinfoById(Long id)
    {
        return fhIndexPostinfoMapper.selectFhIndexPostinfoById(id);
    }

    /**
     * 查询发布信息列表
     *
     * @param fhIndexPostinfo 发布信息
     * @return 发布信息
     */
    @Override
    public List<FhIndexPostinfo> selectFhIndexPostinfoList(FhIndexPostinfo fhIndexPostinfo)
    {
        return fhIndexPostinfoMapper.selectFhIndexPostinfoList(fhIndexPostinfo);
    }

    /**
     * 新增发布信息
     *
     * @param fhIndexPostinfo 发布信息
     * @return 结果
     */
    @Override
    public FhIndexPostinfo insertFhIndexPostinfo(FhIndexPostinfo fhIndexPostinfo)
    {
        fhIndexPostinfo.setCreateTime(LocalDateTime.now());
        fhIndexPostinfoMapper.insertFhIndexPostinfo(fhIndexPostinfo);
        return fhIndexPostinfo;
    }

    /**
     * 修改发布信息
     *
     * @param fhIndexPostinfo 发布信息
     * @return 结果
     */
    @Override
    public int updateFhIndexPostinfo(FhIndexPostinfo fhIndexPostinfo)
    {
        fhIndexPostinfo.setUpdateTime(LocalDateTime.now());
        return fhIndexPostinfoMapper.updateFhIndexPostinfo(fhIndexPostinfo);
    }

    /**
     * 批量删除发布信息
     *
     * @param ids 需要删除的发布信息主键
     * @return 结果
     */
    @Override
    public int deleteFhIndexPostinfoByIds(Long[] ids)
    {
        return fhIndexPostinfoMapper.deleteFhIndexPostinfoByIds(ids);
    }

    /**
     * 删除发布信息信息
     *
     * @param id 发布信息主键
     * @return 结果
     */
    @Override
    public int deleteFhIndexPostinfoById(Long id)
    {
        return fhIndexPostinfoMapper.deleteFhIndexPostinfoById(id);
    }


    //根据好友id数组，以及时间倒序查询捕获表
    @Override
    public List<FhIndexPostinfo> selectFhIndexPostinfoListByIds(Long[] friends) {
        return fhIndexPostinfoMapper.selectFhIndexPostinfoListByIds(friends);
    }


    //根据天数，月份，鱼类id筛选渔获信息
    @Override
    public List<FhIndexPostinfo> screeningCatchList(ScreeningCatchDto screeningCatchDto) {
        List<FhIndexPostinfo> fhIndexPostinfoVo = new ArrayList<>();

        //先根据时间筛选出捕获信息列表，然后再筛选鱼类id;
        int day = screeningCatchDto.getDay().intValue();
        int month = screeningCatchDto.getMonth().intValue();
        Long fishId = screeningCatchDto.getFishId();
        String fishid = String.valueOf(fishId);
        LocalDate now = LocalDate.now();
        LocalDate localDate = LocalDate.of(now.getYear(), month, 15);
        //日期上限
        LocalDate endTime= localDate.plusDays(day);
        //日期下限
        LocalDate startTime = localDate.plusDays(-day);
        TimeDto timeDto = new TimeDto(startTime, endTime);
        List<FhIndexPostinfo> postinfoList= fhIndexPostinfoMapper.screeningCatchListByDate(timeDto);
        for (FhIndexPostinfo fhIndexPostinfo : postinfoList) {
            String[] fishIdList = fhIndexPostinfo.getFishIds().split(",");
            for (String s : fishIdList) {
                if (fishid.equals(s)) {
                    fhIndexPostinfoVo.add(fhIndexPostinfo);
                    break;
                }
            }
        }
        return fhIndexPostinfoVo;
    }

    @Override
    public List<FhIndexPostinfo> selectFhIndexPostinfoListSort(Long userId, String sortColumn, String sortOrder) {
        return fhIndexPostinfoMapper.selectFhIndexPostinfoListSort(userId,sortColumn ,sortOrder);
    }

    @Override
    public List<FhIndexPostinfoAndIsLike> selectFhIndexPostinfoListAndIsLike(Long userId) {
        return fhIndexPostinfoMapper.selectFhIndexPostinfoListAndIsLike(userId);
    }

    @Override
    public List<FhIndexPostinfoAndIsLike> selectFhIndexPostinfoListAndIsLikeByIds(Long userId, ArrayList<Long> friends) {
        return fhIndexPostinfoMapper.selectFhIndexPostinfoListAndIsLikeByIds(userId,friends);
    }

    @Override
    public List<FhIndexPostinfoAndIsLike> selectFhIndexPostinfoListAndIsLikeByNW(String longitude, String latitude, Long userId) {
        return fhIndexPostinfoMapper.selectFhIndexPostinfoListAndIsLikeByNW(longitude,latitude,userId);
    }

    @Override
    public List<FhIndexPostinfoAndIsLike> selectFhIndexPostinfoListAndIsLikeByTerms(String terms, Long userId) {
        return fhIndexPostinfoMapper.selectFhIndexPostinfoListAndIsLikeByTerms(terms, userId);
    }

    @Override
    public PostInfoDtoX postInforanking(PostinfoDto postinfo) {
        //获取当前用户好友
        UserInfo member = (UserInfo) LocalDataUtil.getVar(Constants.MEMBER_INFO);
        FhChatFriend fhChatFriend = new FhChatFriend();
        fhChatFriend.setUserId(member.getId());
        List<FhChatFriend> friends = fhChatFriendMapper.selectFhChatFriendList(fhChatFriend);
        if (friends == null || friends.isEmpty()) {
            return new PostInfoDtoX();
        }

        // 2. 提取好友的 userIds
        List<Long> friendIds = new ArrayList<>();
        for (FhChatFriend f : friends) {
            friendIds.add(f.getFriendId());
        }

        // 4. 查询所有好友的鱼获记录
        List<PostinfoDto> allPosts = new ArrayList<>();
        for (Long friendId : friendIds) {
            List<PostinfoDto> posts = fhIndexPostinfoMapper.postInforanking(friendId,postinfo.getStatus());
            if (posts != null && !posts.isEmpty()) {
                allPosts.addAll(posts);
            }
        }
        //查询自己的鱼获记录
        List<PostinfoDto> postsDto = fhIndexPostinfoMapper.postInforanking(member.getId(),postinfo.getStatus());
        if (postsDto != null && !postsDto.isEmpty()) {
            allPosts.addAll(postsDto);
        }

        //塞值
        PostInfoDtoX postInfoDtoX = new PostInfoDtoX();
        postInfoDtoX.setPostInfoDtoList(allPosts);
        postInfoDtoX.setMyPostList(postsDto);

        return postInfoDtoX;
    }


    @Override
    public PostInfoDtoX areaRanking(PostinfoDto postinfo) {
        //根据经纬度查询
        List<PostinfoDto> postinfoDtos = fhIndexPostinfoMapper.areaRanking(postinfo);
        //查询本人数据
        Long userId = LocalUserInfoUtil.getLocalUserInfo().getId();
        postinfo.setUserId(userId);
        List<PostinfoDto> myPosts = fhIndexPostinfoMapper.areaRanking(postinfo);
        //塞值
        PostInfoDtoX postInfoDtoX = new PostInfoDtoX();
        postInfoDtoX.setPostInfoDtoList(postinfoDtos);
        postInfoDtoX.setMyPostList(myPosts);
        return postInfoDtoX;
    }

    @Override
    public List<FhMapFishtype> seizeFhsh(PostinfoDto postinfo, Pageable page) {
        // 查询所有 fish_ids 字符串列表
        List<String> allFishIdStrings = fhIndexPostinfoMapper.selectFishIdsByUserId(postinfo.getUserId());

        List<FhMapFishtype> resultList = new ArrayList<>();

        for (String fishIdStr : allFishIdStrings) {
            if (StringUtils.hasText(fishIdStr)) {
                String[] ids = fishIdStr.split(",");
                for (String id : ids) {
                    String trimmedId = id.trim();
                    if (StringUtils.hasText(trimmedId)) {
                        Long fishId = Long.parseLong(trimmedId);

                        // 查询当前 fishId 对应的信息
                        FhMapFishtype dto = fhMapFishtypeMapper.selectFhMapFishtypeById(fishId);
                        if (dto == null) continue;

                        boolean found = false;
                        // 查找是否已有该 fishId 的 dto 在列表中
                        for (FhMapFishtype existing : resultList) {
                            if (existing.getId().equals(dto.getId())) {
                                existing.setCount(existing.getCount() + 1); // 已存在，计数+1
                                found = true;
                                break;
                            }
                        }

                        if (!found) {
                            dto.setCount(1L); // 第一次出现，设置为1
                            resultList.add(dto);
                        }
                    }
                }
            }
        }

        return resultList;
    }



    @Override
    public List<FhMapFishtype> nearbyFish(PostinfoDto postinfo, Pageable page) {
        if (page != null){
            PageHelper.startPage(page.getPageNumber() + 1, page.getPageSize());
        }
        FhIndexPostinfo fhIndexPostinfo = new FhIndexPostinfo();
        fhIndexPostinfo.setLongitude(postinfo.getLongitude());
        fhIndexPostinfo.setLatitude(postinfo.getLatitude());
        List<FhIndexPostinfo> fhIndexPostinfoList = fhIndexPostinfoMapper.selectFhIndexPostinfoList(fhIndexPostinfo);
        if(fhIndexPostinfoList.isEmpty()){
            List<FhMapFishtype> fhMapFishtypes = new ArrayList<>();
            return fhMapFishtypes;
        }
        List<String> fishIdList = new ArrayList<>();
        for (FhIndexPostinfo indexPostinfo : fhIndexPostinfoList) {
            String[] split = indexPostinfo.getFishIds().split(",");
            fishIdList.addAll(Arrays.asList(split));
        }
        HashSet<String> fishIds = new HashSet<>(fishIdList);
        List<String> strings = new ArrayList<>(fishIds);
        //鱼类ids
        List<Long> idList = new ArrayList<>();
        for (String string : strings) {
            idList.add(Long.parseLong(string));
        }
        //批量查询鱼类id
        List<FhMapFishtype> fhMapFishtypes = fhMapFishtypeMapper.selectListByFishidList(idList);

        return fhMapFishtypes;
    }

    @Override
    public FhIndexPostinfoVO contFriends(Long userId) {
        FhIndexPostinfoVO fhIndexPostinfoVO = new FhIndexPostinfoVO();
        //统计已抓鱼获
        Long contFish = fhIndexPostinfoMapper.contFriends(userId);
        if (contFish != null){
            fhIndexPostinfoVO.setContFish(contFish);
        }

        //统计已抓鱼种
        List<String> fishIdStrings = fhIndexPostinfoMapper.selectFishIdsByUserId(userId);
        Map<Long, Integer> fishCountMap = new HashMap<>();
        Set<Long> uniqueFishIds = new HashSet<>();

        for (String fishIdStr : fishIdStrings) {
            if (StringUtils.hasText(fishIdStr)) {
                String[] ids = fishIdStr.split(",");
                for (String id : ids) {
                    String trimmedId = id.trim();
                    if (StringUtils.hasText(trimmedId)) {
                        try {
                            Long fishId = Long.parseLong(trimmedId);
                            uniqueFishIds.add(fishId);
                            fishCountMap.put(fishId, fishCountMap.getOrDefault(fishId, 0) + 1);
                        } catch (NumberFormatException ignored) {
                            // 忽略非法数据
                        }
                    }
                }
            }
        }

        // 获取出现次数最多的鱼种
        if (!fishCountMap.isEmpty()) {
            Map.Entry<Long, Integer> maxEntry = Collections.max(fishCountMap.entrySet(),
                    Map.Entry.comparingByValue());
            Long mostFrequentFishId = maxEntry.getKey();

            // 查询该鱼种的信息（包含图片）
            FhMapFishtype fishTypeInfo = fhMapFishtypeMapper.selectFhMapFishtypeById(mostFrequentFishId);
            if (fishTypeInfo != null) {
                fhIndexPostinfoVO.setFishUrl(fishTypeInfo.getFishImage()); // 假设 imageUrl 是图片字段名
            }
        }

        // 设置到 VO 中
        fhIndexPostinfoVO.setContFriendType((long) uniqueFishIds.size());
        //统计已标记
        Long contSign = fhMypunctuationService.contSign(userId);
        if (contSign != null){
            fhIndexPostinfoVO.setContSign(contSign);
        }

        return fhIndexPostinfoVO;
    }


}
